package com.wolfsea.defineviewpageindicator
import android.content.Context
import android.graphics.PointF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View

/*
* 多点触摸(配合型/协作型):所有触摸到 View 的 pointer 共同起作用
* */
class MultiTouchView2 @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : View(context, attributeSet) {

    //按下时的坐标
    private val mDownPointF by lazy {
        PointF()
    }

    //偏移坐标
    private val mOffsetPointF by lazy {
        PointF()
    }

    //上次偏移坐标
    private val mLastOffsetPointF by lazy {
        PointF()
    }

    //所有pointer的焦点(中心点)
    private val mFocusPointF by lazy {
        PointF()
    }

    //pointer的数量
    private var mPointerCount = 0

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        performClick()

        mPointerCount = event?.pointerCount ?: 0
        var sumX = 0F
        var sumY = 0F

        //是否是pointer_up事件
        val mIsPointerUp = event?.actionMasked == MotionEvent.ACTION_POINTER_UP

        for (i in 0.until(mPointerCount)) {
            if (!(mIsPointerUp && i == event?.actionIndex)) {
                //抬起的手指不用计算
                sumX += event?.getX(i) ?: 0F
                sumY += event?.getY(i) ?: 0F
            }
        }

        if (mIsPointerUp) {
            //手指总数量减1
            mPointerCount -= 1
        }

        //计算焦点
        mFocusPointF.x = sumX / mPointerCount
        mFocusPointF.y = sumY / mPointerCount

        when (event?.actionMasked) {
            MotionEvent.ACTION_DOWN,
            MotionEvent.ACTION_POINTER_DOWN,
            MotionEvent.ACTION_POINTER_UP -> {
                mDownPointF.x = mFocusPointF.x
                mDownPointF.y = mFocusPointF.y

                mLastOffsetPointF.x = mOffsetPointF.x
                mLastOffsetPointF.y = mOffsetPointF.y
            }
            MotionEvent.ACTION_MOVE -> {
                mOffsetPointF.x = mLastOffsetPointF.x + mFocusPointF.x - mDownPointF.x
                mOffsetPointF.y = mLastOffsetPointF.y + mFocusPointF.y - mDownPointF.y
                invalidate()
            }
        }

        return true
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }

}